package com.deli.talkbetter;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.deli.talkbetter.databinding.FragmentSecondBinding;
import com.deli.talkbetter.llm.MaaS;
import com.deli.talkbetter.llm.GrammarQuestion;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SecondFragment extends Fragment {

    private FragmentSecondBinding binding;
    private MaaS maas;
    private List<GrammarQuestion> questions;
    private int currentQuestionIndex = 0;
    private Handler progressHandler;
    private Runnable progressRunnable;
    private int progress = 0;
    private final int maxProgress = 25; // 15秒满格
    private int correctCount = 0; // 答对题数统计
    private boolean[] questionAnswered; // 题目是否已答
    private boolean[] questionCorrect; // 题目是否答对
    private Handler translationHandler;
    private Runnable translationRunnable;
    private PopupWindow translationPopup; // 添加PopupWindow用于显示翻译

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentSecondBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化 MaaS 实例
        maas = new MaaS();
        
        // 设置回调
        maas.setQuestionsCallback(new MaaS.QuestionsCallback() {
            @Override
            public void onQuestionsLoaded(List<GrammarQuestion> loadedQuestions) {
                stopProgress(); // 停止进度更新
                questions = loadedQuestions;
                if (questions != null && !questions.isEmpty()) {
                    currentQuestionIndex = 0;
                    // 初始化答题统计数组
                    questionAnswered = new boolean[questions.size()];
                    questionCorrect = new boolean[questions.size()];
                    requireActivity().runOnUiThread(() -> {
                        binding.questionTitle.setText("正在加载题目...");
                        binding.progressBar.setVisibility(View.GONE); // 隐藏进度条
                        displayQuestion();
                        updateNavigationButtons();
                    });
                }
            }

            @Override
            public void onError(String error) {
                stopProgress(); // 停止进度更新
                requireActivity().runOnUiThread(() -> {
                    binding.questionTitle.setText("题目加载失败");
                    binding.progressBar.setVisibility(View.GONE); // 隐藏进度条
                    // 题目加载失败时也隐藏选项组
                    binding.optionsGroup.setVisibility(View.GONE);
                    Toast.makeText(requireContext(), "获取题目失败: " + error, Toast.LENGTH_LONG).show();
                });
            }
        });
        
        // 调用大模型获取题目
        maas.fetchQuestionsFromAPI(requireContext());
        startProgress(); // 开始进度更新
        
        // 在开始加载时隐藏选项组
        binding.optionsGroup.setVisibility(View.GONE);
        
        // 设置选项选择监听器
        binding.optionsGroup.setOnCheckedChangeListener((group, checkedId) -> checkAnswer());
        
        // 设置上一题按钮点击事件
        binding.prevQuestionButton.setOnClickListener(v -> showPrevQuestion());
        
        // 设置下一题按钮点击事件
        binding.nextQuestionButton.setOnClickListener(v -> showNextQuestion());
    }

    private void startProgress() {
        binding.progressBar.setVisibility(View.VISIBLE);
        binding.progressBar.setMax(maxProgress); // 设置最大进度
        binding.progressBar.setProgress(0); // 初始进度为0
        
        progress = 0;
        progressHandler = new Handler(Looper.getMainLooper());
        progressRunnable = new Runnable() {
            @Override
            public void run() {
                progress++;
                binding.progressBar.setProgress(progress);
                
                if (progress < maxProgress) {
                    // 每秒更新一次进度
                    progressHandler.postDelayed(this, 1000);
                }
            }
        };
        
        // 开始进度更新
        progressHandler.postDelayed(progressRunnable, 1000);
    }
    
    private void stopProgress() {
        if (progressHandler != null && progressRunnable != null) {
            progressHandler.removeCallbacks(progressRunnable);
            progressHandler = null;
            progressRunnable = null;
        }
    }

    private void displayQuestion() {
        if (questions != null && !questions.isEmpty() && currentQuestionIndex < questions.size()) {
            GrammarQuestion currentQuestion = questions.get(currentQuestionIndex);
            
            // 显示当前题目序号和总题数，并添加点击事件处理
            String questionText = "题目 " + (currentQuestionIndex + 1) + "/" + questions.size() + ": " + currentQuestion.getQuestion();
            SpannableString questionSpannable = new SpannableString(questionText);
            addClickSpans(questionSpannable, questionText, binding.questionTitle);
            binding.questionTitle.setText(questionSpannable);
            binding.questionTitle.setMovementMethod(LinkMovementMethod.getInstance());
            
            String[] options = currentQuestion.getOptions();
            if (options.length == 4) {
                // 为每个选项添加点击事件处理
                SpannableString optionASpannable = new SpannableString(options[0]);
                addClickSpans(optionASpannable, options[0], binding.optionA);
                binding.optionA.setText(optionASpannable);
                binding.optionA.setMovementMethod(LinkMovementMethod.getInstance());
                
                SpannableString optionBSpannable = new SpannableString(options[1]);
                addClickSpans(optionBSpannable, options[1], binding.optionB);
                binding.optionB.setText(optionBSpannable);
                binding.optionB.setMovementMethod(LinkMovementMethod.getInstance());
                
                SpannableString optionCSpannable = new SpannableString(options[2]);
                addClickSpans(optionCSpannable, options[2], binding.optionC);
                binding.optionC.setText(optionCSpannable);
                binding.optionC.setMovementMethod(LinkMovementMethod.getInstance());
                
                SpannableString optionDSpannable = new SpannableString(options[3]);
                addClickSpans(optionDSpannable, options[3], binding.optionD);
                binding.optionD.setText(optionDSpannable);
                binding.optionD.setMovementMethod(LinkMovementMethod.getInstance());
            }
            
            // 清除之前的选择
            binding.optionsGroup.clearCheck();
            
            // 隐藏答案解析区域和统计信息
            binding.answerResultLayout.setVisibility(View.GONE);
            binding.statisticsText.setVisibility(View.GONE);
            
            // 显示选项和相关控件
            binding.optionsGroup.setVisibility(View.VISIBLE);
            updateNavigationButtons();
            binding.progressBar.setVisibility(View.GONE); // 隐藏进度条
        }
    }
    
    // 为文本中的单词添加点击事件
    private void addClickSpans(SpannableString spannableString, String text, View view) {
        // 使用正则表达式匹配英文单词
        Pattern wordPattern = Pattern.compile("[a-zA-Z]+");
        Matcher matcher = wordPattern.matcher(text);
        
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String word = matcher.group();
            
            // 对于选项文本，跳过开头的 A, B, C, D 字母
            boolean isOptionText = (view == binding.optionA || view == binding.optionB || 
                                   view == binding.optionC || view == binding.optionD);
            if (isOptionText && start == 0 && end == 1 && 
                (word.equals("A") || word.equals("B") || word.equals("C") || word.equals("D"))) {
                continue; // 跳过选项开头的 A, B, C, D 字母
            }
            
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    // 获取单词翻译
                    fetchAndShowTranslation(word, view);
                }
                
                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false); // 不显示下划线
                }
            };
            
            spannableString.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    
    // 获取并显示单词翻译
    private void fetchAndShowTranslation(String word, View view) {
        // 取消之前的隐藏翻译任务（如果有的话）
        if (translationHandler != null && translationRunnable != null) {
            translationHandler.removeCallbacks(translationRunnable);
        }
        
        // 获取翻译
        maas.fetchWordTranslation(requireContext(), word, new MaaS.TranslationCallback() {
            @Override
            public void onTranslationLoaded(String translation) {
                requireActivity().runOnUiThread(() -> {
                    // 显示翻译结果PopupWindow
                    TextView translationText = new TextView(requireContext());
                    translationText.setText(translation);  // 直接显示翻译结果，不加前缀
                    translationText.setBackgroundColor(Color.WHITE);
                    translationText.setPadding(20, 20, 20, 20);
                    
                    if (translationPopup != null && translationPopup.isShowing()) {
                        translationPopup.dismiss();
                    }
                    
                    translationPopup = new PopupWindow(translationText, 
                            ViewGroup.LayoutParams.WRAP_CONTENT, 
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    translationPopup.setOutsideTouchable(true);
                    translationPopup.setFocusable(false);
                    translationPopup.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                    
                    // 使用showAsDropDown来更精确地定位PopupWindow
                    translationPopup.showAsDropDown(view, 50, -100);
                    
                    // 2秒后自动隐藏翻译
                    scheduleHideTranslation();
                });
            }
            
            @Override
            public void onError(String error) {
                requireActivity().runOnUiThread(() -> {
                    // 显示错误信息
                    TextView errorText = new TextView(requireContext());
                    errorText.setText("获取 \"" + word + "\" 的翻译失败: " + error);
                    errorText.setBackgroundColor(Color.WHITE);
                    errorText.setPadding(20, 20, 20, 20);
                    
                    if (translationPopup != null && translationPopup.isShowing()) {
                        translationPopup.dismiss();
                    }
                    
                    translationPopup = new PopupWindow(errorText, 
                            ViewGroup.LayoutParams.WRAP_CONTENT, 
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    translationPopup.setOutsideTouchable(true);
                    translationPopup.setFocusable(false);
                    translationPopup.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                    
                    // 使用showAsDropDown来更精确地定位PopupWindow
                    translationPopup.showAsDropDown(view, 50, -100);
                    
                    // 2秒后自动隐藏翻译
                    scheduleHideTranslation();
                });
            }
        });
    }
    
    // 安排隐藏翻译
    private void scheduleHideTranslation() {
        translationHandler = new Handler(Looper.getMainLooper());
        translationRunnable = new Runnable() {
            @Override
            public void run() {
                if (translationPopup != null && translationPopup.isShowing()) {
                    translationPopup.dismiss();
                }
            }
        };
        translationHandler.postDelayed(translationRunnable, 2000); // 2秒后隐藏
    }
    
    // 隐藏翻译
    private void hideTranslation() {
        if (translationPopup != null && translationPopup.isShowing()) {
            translationPopup.dismiss();
        }
        if (translationHandler != null && translationRunnable != null) {
            translationHandler.removeCallbacks(translationRunnable);
            translationHandler = null;
            translationRunnable = null;
        }
    }
    
    private void updateNavigationButtons() {
        if (questions == null || questions.isEmpty()) {
            binding.navigationButtons.setVisibility(View.GONE);
            return;
        }
        
        // 更新上一题按钮状态
        binding.prevQuestionButton.setEnabled(currentQuestionIndex > 0);
        
        // 更新下一题按钮状态
        binding.nextQuestionButton.setEnabled(currentQuestionIndex < questions.size() - 1);
        
        // 显示导航按钮
        binding.navigationButtons.setVisibility(View.VISIBLE);
    }
    
    private void showPrevQuestion() {
        if (currentQuestionIndex > 0) {
            currentQuestionIndex--;
            displayQuestion();
        }
    }
    
    private void showNextQuestion() {
        if (questions != null && currentQuestionIndex < questions.size() - 1) {
            currentQuestionIndex++;
            displayQuestion();
        }
    }

    private void checkAnswer() {
        if (questions == null || questions.isEmpty() || currentQuestionIndex >= questions.size()) {
            return;
        }
        
        GrammarQuestion currentQuestion = questions.get(currentQuestionIndex);
        RadioGroup optionsGroup = binding.optionsGroup;
        int selectedId = optionsGroup.getCheckedRadioButtonId();
        
        if (selectedId == -1) {
            return;
        }
        
        // 获取选中的选项索引
        int selectedIndex = -1;
        RadioButton selectedRadioButton = getView().findViewById(selectedId);
        if (selectedRadioButton == binding.optionA) selectedIndex = 0;
        else if (selectedRadioButton == binding.optionB) selectedIndex = 1;
        else if (selectedRadioButton == binding.optionC) selectedIndex = 2;
        else if (selectedRadioButton == binding.optionD) selectedIndex = 3;
        
        // 标记题目已答
        questionAnswered[currentQuestionIndex] = true;
        
        // 显示答案结果
        String[] options = currentQuestion.getOptions();
        String correctAnswer = options[currentQuestion.getCorrectAnswerIndex()];
        
        if (selectedIndex == currentQuestion.getCorrectAnswerIndex()) {
            binding.answerResultText.setText("回答正确！");
            binding.answerResultText.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
            questionCorrect[currentQuestionIndex] = true;
        } else {
            binding.answerResultText.setText("回答错误！正确答案是: " + correctAnswer);
            binding.answerResultText.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
            questionCorrect[currentQuestionIndex] = false;
        }
        
        binding.answerExplanationText.setText(currentQuestion.getExplanation());
        binding.answerResultLayout.setVisibility(View.VISIBLE);
        
        // 如果是最后一题，显示统计信息
        if (currentQuestionIndex == questions.size() - 1) {
            showStatistics();
        }
    }
    
    private void showStatistics() {
        if (questionAnswered == null || questionCorrect == null) {
            return;
        }
        
        int answeredCount = 0;
        correctCount = 0;
        
        for (int i = 0; i < questionAnswered.length; i++) {
            if (questionAnswered[i]) {
                answeredCount++;
            }
            if (questionCorrect[i]) {
                correctCount++;
            }
        }
        
        String statistics = "共答" + answeredCount + "题，答对" + correctCount + "题";
        binding.statisticsText.setText(statistics);
        binding.statisticsText.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopProgress(); // 确保在视图销毁时停止进度更新
        hideTranslation(); // 隐藏翻译
        binding = null;
    }

}